package com.wowangz.cms.syscore.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import com.wowangz.cms.syscore.pojo.FtpProperty;

import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpProtocolException;

/**
 * ftp上传下载工具类
 * @author xiakai
 *
 */
public class FtpUtil 
{
	
	private int maxBufferSize = 2 * (1024 * 1024);

	private FtpClient ftpClient = null;
	
	
	public static void main(String [] arg)
	{
		
		
	}

	/**
	 * connectServer 连接ftp服务器
	 * 
	 * @throws java.io.IOException
	 * @param path
	 *            文件夹，空代表根目录
	 * @param password
	 *            密码
	 * @param user
	 *            登陆用户
	 * @param server
	 *            服务器地址
	 * @throws FtpProtocolException 
	 */
	public void connectServer() throws IOException, FtpProtocolException {
		// server：FTP服务器的IP地址；user:登录FTP服务器的用户名
		// password：登录FTP服务器的用户名的口令；path：FTP服务器上的路径
		
		FtpProperty ftpProperty =(FtpProperty)SpringUtil.getBean("ftpProperty");
		
		ftpClient = FtpClient.create(ftpProperty.getFtpIp());
		ftpClient.login(ftpProperty.getFtpUser(),ftpProperty.getFtpPassword().toCharArray());

		// 用2进制上传、下载
		ftpClient.setBinaryType();
	}

	/**
	 * upload 上传文件
	 * 
	 * @throws java.lang.Exception
	 * @return -1 文件不存在 -2 文件内容为空 >0 成功上传，返回文件的大小
	 * @param fileInput
	 *            上传的文件流
	 * @param filename
	 *            上传的文件
	 */
	public long upload(InputStream fileInput, String newname) throws Exception {
		long result = 0;
		OutputStream os = null;

		try {
			os = ftpClient.putFileStream(newname,true);
			byte[] bytes = new byte[maxBufferSize];
			int c;
			while ((c = fileInput.read(bytes)) != -1) {
				os.write(bytes, 0, c);
			}
		} finally {
			if (fileInput != null) {
				fileInput.close();
			}
			if (os != null) {
				os.close();
			}
		}

		return result;
	}

	/**
	 * download 从ftp下载文件到本地
	 * 
	 * @throws java.lang.Exception
	 * @return
	 * @param newfilename
	 *            本地生成的文件名
	 * @param filename
	 *            服务器上的文件名
	 */
	public void download(String downloadFileName, String showName,HttpServletResponse response) throws Exception {
		InputStream is = null;
		OutputStream out = null;
		try {
			is = ftpClient.getFileStream(downloadFileName);

			 response.reset();    
	            response.addHeader("Content-Disposition", "attachment;filename=" + 
	            		URLEncoder.encode(showName, "UTF-8"));
             //得到向客户端输出二进制数据的对象 
	            out = new BufferedOutputStream(response.getOutputStream()); 
			
			if (showName.toUpperCase().indexOf(".DOC") > -1) 
			{
				response.setContentType("application/msword");
			} 
			else	
			{   
                 //设置返回的文件类型
				response.setContentType("application/octet-stream"); 
			}
			 	byte[] bytes = new byte[maxBufferSize];
	            int c;
	            long result = 0;
	            while ((c = is.read(bytes)) != -1) {
	            	out.write(bytes, 0, c);
					result = result + c;
				}
	            
	            response.addHeader("Content-Length", "" + result);
	            out.flush();
			
			
		} finally {
			try
        	{
        		if (is != null)
        		{
        			is.close();
        		}
        		
        		if (out != null)
        		{
        			out.close();
        		}
        	}
        	catch(Exception e)
        	{
        		throw e;
        	}
		}
	}
	
	/** 
	 *  download 
	 *  从ftp下载文件到本地 
	 * @throws java.lang.Exception 
	 * @return  
	 * @param reportFtpClient FTP连接对象
	 * @param ftpFilename ftp上保存的文件名 
	 * @param newfilename 下载到服务器上的文件名 
	 */
	public long downloadReport(String ftpFilename, String newfilename) throws Exception {
		long result = 0;
		InputStream is = null;
		FileOutputStream os = null;
		try {
			is = ftpClient.getFileStream(ftpFilename);
			File outfile = new File(newfilename);
			os = new FileOutputStream(outfile);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
				result = result + c;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		}
		return result;
	}
	
	/**
	 * delete ftp上的文件
	 * 
	 * @throws java.lang.Exception
	 * @return
	 * @param newfilename
	 *            本地生成的文件名
	 * @param filename
	 *            服务器上的文件名
	 */
	public void delete(String downloadFileName) throws Exception {
		ftpClient.deleteFile(downloadFileName);
	}

	/**
	 * closeServer 断开与ftp服务器的链接
	 * 
	 * @throws java.io.IOException
	 */
	public void closeServer() throws IOException {
		if (ftpClient != null) {
			ftpClient.close();
		}
	}
}